import React, { useState, useEffect } from 'react';
import FilterButtons from './components/FilterButtons';
import ProjectGrid from './components/ProjectGrid';
import Skeleton from './components/Skeleton'; // Assuming Skeleton component is in the same directory
import useTheme from './hooks/useTheme';
import Header from './components/Header'; // 导入共用的Header组件
import { Navigate, Routes, Route, useNavigate } from 'react-router-dom';
import ProjectDetail from './pages/ProjectDetail/ProjectDetail';
import LoginPage from './pages/LoginPage';
import TestApiPage from './pages/TestApiPage';
import TaskManagementPage from './pages/TaskManagementPage';
import AddVersionPage from './pages/AddVersionPage'; // 导入新增版本页面
import { AuthProvider, useAuth } from './context/AuthContext';
import { wxAuthConfig } from './config';
import { Layout, Button, Space, Avatar, Dropdown, Menu, Modal, Form, Input, Select, message } from 'antd';
import { UserOutlined, LogoutOutlined, PlusOutlined } from '@ant-design/icons';
import api from './utils/api';
// import { TaskIcon, ProfileIcon } from './icons'; // Assuming icons are in the same directory

// 技术分类常量
const TECH_CATEGORIES = {
  ALL: '全部',
  JAVA: 'Java',
  KOTLIN: 'Kotlin',
  PYTHON: 'Python',
  REACT: 'React',
  FLUTTER: 'Flutter',
  ANDROID: 'Android'
};

// 技术分类选项数组（用于过滤器）
const TECH_CATEGORY_FILTERS = [
  TECH_CATEGORIES.ALL,
  TECH_CATEGORIES.JAVA,
  TECH_CATEGORIES.KOTLIN,
  TECH_CATEGORIES.PYTHON,
  TECH_CATEGORIES.REACT,
  TECH_CATEGORIES.FLUTTER,
  TECH_CATEGORIES.ANDROID
];

// 技术分类选项数组（用于表单选择器）
const TECH_CATEGORY_OPTIONS = [
  { value: 'JAVA', label: TECH_CATEGORIES.JAVA },
  { value: 'KOTLIN', label: TECH_CATEGORIES.KOTLIN },
  { value: 'PYTHON', label: TECH_CATEGORIES.PYTHON },
  { value: 'REACT', label: TECH_CATEGORIES.REACT },
  { value: 'FLUTTER', label: TECH_CATEGORIES.FLUTTER },
  { value: 'ANDROID', label: TECH_CATEGORIES.ANDROID }
];

// 项目类型常量
const PROJECT_TYPES = {
  ALL: '全部',
  PERSONAL: '个人',
  COMPANY: '公司'
};

// 项目类型选项数组（用于过滤器）
const PROJECT_TYPE_FILTERS = [
  PROJECT_TYPES.ALL,
  PROJECT_TYPES.PERSONAL,
  PROJECT_TYPES.COMPANY
];

// 项目类型选项数组（用于表单选择器）
const PROJECT_TYPE_OPTIONS = [
  { value: 'PERSONAL', label: PROJECT_TYPES.PERSONAL },
  { value: 'COMPANY', label: PROJECT_TYPES.COMPANY }
];

function App() {
  const [typeFilter, setTypeFilter] = useState('全部');
  const [categoryFilter, setCategoryFilter] = useState('全部');
  const [darkMode, setDarkMode] = useTheme();
  const [loading, setLoading] = useState(true);
  const [projectList, setProjectList] = useState([]);

  // 获取项目列表数据
  const fetchProjects = async () => {
    setLoading(true);
    try {
      const response = await api.get('/api/project/list');
      if (response.data && response.data.code === '200') {
        setProjectList(response.data.data || []);
      } else {
        console.error('获取项目列表失败:', response.data.message);
        message.error('获取项目列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取项目列表异常:', error);
      message.error('获取项目列表异常: ' + (error.response?.data?.message || error.message));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProjects();
  }, []);

  const filteredProjects = projectList.filter(project => {
    const typeMatch = typeFilter === PROJECT_TYPES.ALL || 
      (typeFilter === PROJECT_TYPES.PERSONAL && project.projectType === 'PERSONAL') ||
      (typeFilter === PROJECT_TYPES.COMPANY && project.projectType === 'COMPANY');
    
    const categoryMatch = categoryFilter === TECH_CATEGORIES.ALL || 
      (project.techCategory === categoryFilter.toUpperCase());
    
    return typeMatch && categoryMatch;
  });

  const navigate = useNavigate();
  const handleTask = () => navigate('/task-management');
  const handleResumeMode = () => console.log('简历模式');
  const handleNewProject = () => console.log('新建项目');
  const showProfile = () => console.log('个人中心');

  return (
    <AuthProvider>
      <Routes>
        <Route path="/login" element={<LoginPage />} />
        <Route path="/test-api" element={<TestApiPage />} />
        <Route 
          path="/" 
          element={
            <RequireAuth>
              <MainLayout 
                darkMode={darkMode} 
                setDarkMode={setDarkMode}
                typeFilter={typeFilter}
                setTypeFilter={setTypeFilter}
                categoryFilter={categoryFilter}
                setCategoryFilter={setCategoryFilter}
                loading={loading}
                filteredProjects={filteredProjects}
                handleTask={handleTask}
                handleResumeMode={handleResumeMode}
                handleNewProject={handleNewProject}
                showProfile={showProfile}
                fetchProjects={fetchProjects}
              />
            </RequireAuth>
          } 
        />
        <Route path="/project/:id" element={<ProjectDetail />} />
        <Route path="/project/:id/add-version" element={
          <RequireAuth>
            <AddVersionPage />
          </RequireAuth>
        } />
        <Route path="/task-management" element={
          <RequireAuth>
            <TaskManagementPage />
          </RequireAuth>
        } />
      </Routes>
    </AuthProvider>
  );
}

// 主布局组件，包含头部和内容
function MainLayout({ 
  darkMode, 
  setDarkMode, 
  typeFilter, 
  setTypeFilter, 
  categoryFilter, 
  setCategoryFilter, 
  loading, 
  filteredProjects,
  handleTask,
  handleResumeMode,
  handleNewProject,
  showProfile,
  fetchProjects
}) {
  const { user, logout } = useAuth();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  
  // 打开新建项目弹窗
  const showNewProjectModal = () => {
    setIsModalVisible(true);
  };
  
  // 关闭弹窗
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };
  
  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setSubmitting(true);
      
      console.log('提交新项目数据:', values);
      
      try {
        const response = await api.post('/api/project/create', values);
        
        if (response.data && (response.data.code === 200 || response.data.code === '200')) {
          message.success('项目创建成功');
          setIsModalVisible(false);
          form.resetFields();
          fetchProjects(); // 这里可以添加刷新项目列表的逻辑
        } else {
          message.error(response.data.message || '创建失败，请重试');
        }
      } catch (error) {
        console.error('创建项目失败:', error);
        message.error('创建失败: ' + (error.response?.data?.message || error.message));
      } finally {
        setSubmitting(false);
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };
  
  const handleLogout = () => {
    logout();
    window.location.href = '/login';
  };
  
  const userMenu = (
    <Menu>
      <Menu.Item key="profile" onClick={showProfile} icon={<UserOutlined />}>
        个人中心
      </Menu.Item>
      <Menu.Item key="logout" onClick={handleLogout} icon={<LogoutOutlined />}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <Layout className={darkMode ? 'dark' : ''} style={{ background: 'var(--bg-color)' }}>
      <Header 
        darkMode={darkMode} 
        setDarkMode={setDarkMode}
        onNewProject={showNewProjectModal}
      />
      <Layout.Content style={{ paddingTop: 84, margin: 0, padding: '2rem 5%' }}>
        <div className="main-content">
          <div className="page-header">
            {/* <div>
              <h1 className="page-title">项目管理系统</h1>
              <p>管理和跟踪您的所有项目</p>
            </div> */}
          </div>
          
          <div className="filters">
            <div className="filter-container">
              <div className="filter-group">
                <h3>项目类型：</h3>
                <FilterButtons
                  filters={PROJECT_TYPE_FILTERS}
                  activeFilter={typeFilter}
                  setFilter={setTypeFilter}
                />
              </div>
  
              <div className="filter-group">
                <h3>技术分类：</h3>
                <FilterButtons
                  filters={TECH_CATEGORY_FILTERS}
                  activeFilter={categoryFilter}
                  setFilter={setCategoryFilter}
                />
              </div>
            </div>
          </div>

          {loading ? (
            <div className="projects-grid">
              {[...Array(6)].map((_, i) => <Skeleton key={i} />)}
            </div>
          ) : (
            <>
              <div className="projects-count">
                共找到 <span>{filteredProjects.length}</span> 个项目
                <Button type="text" onClick={showNewProjectModal} icon={<PlusOutlined />} style={{ marginLeft: '10px' }}>新建项目</Button>
              </div>
              <ProjectGrid projects={filteredProjects} />
            </>
          )}
        </div>
      </Layout.Content>
      
      {/* 新建项目弹窗 */}
      <Modal
        title="新建项目"
        open={isModalVisible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        confirmLoading={submitting}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          name="new_project_form"
          initialValues={{
            projectType: 'PERSONAL',
            techCategory: 'JAVA',
            projectStatus: 'DEVELOPING',
            projectDesc: ''
          }}
        >
          <Form.Item
            name="projectName"
            label="项目名称"
            rules={[{ required: true, message: '请输入项目名称' }]}
          >
            <Input placeholder="请输入项目名称" />
          </Form.Item>
          
          <Form.Item
            name="projectType"
            label="项目类型"
            rules={[{ required: true, message: '请选择项目类型' }]}
          >
            <Select options={PROJECT_TYPE_OPTIONS} />
          </Form.Item>
          
          <Form.Item
            name="techCategory"
            label="技术分类"
            rules={[{ required: true, message: '请选择技术分类' }]}
          >
            <Select options={TECH_CATEGORY_OPTIONS} />
          </Form.Item>
          
          <Form.Item
            name="projectStatus"
            label="项目状态"
            rules={[{ required: true, message: '请选择项目状态' }]}
          >
            <Select>
              <Select.Option value="DEVELOPING">开发中</Select.Option>
              <Select.Option value="COMPLETED">已完成</Select.Option>
              <Select.Option value="ABANDONED">已废弃</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="projectDesc"
            label="项目说明"
            rules={[{ required: false, message: '请输入项目说明' }]}
          >
            <Input.TextArea 
              placeholder="请输入项目说明" 
              rows={3} 
              maxLength={500}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
}

const RequireAuth = ({ children }) => {
  const { user, loading } = useAuth();
  
  // 如果认证状态正在加载中，显示加载状态而不是立即重定向
  if (loading) {
    return <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
      <p>加载中...</p>
    </div>;
  }
  
  // 加载完成后，根据用户状态决定是否重定向
  return user ? children : <Navigate to="/login" replace />;
};

export default App;
